// pages/films/player.js
let app=getApp() 
let pp 
let videoContext
Page({
	data:{
		rateIndex: 2,
		rates: ['0.5', '0.8', '1.0','1.25', '1.5', '2.0', '3.0', '4.0'],
	},
	rates(e){ 
		let rateIndex=e.target.dataset.index 
		this.setData({rateIndex}) 
		let rate=this.data.rates[rateIndex] 
		videoContext.playbackRate(rate-0) 
	},
	loadedmeta(e){ 
		console.log('视频元数据加载完成', e)
		let rateIndex=this.data.rateIndex 
		let rate=this.data.rates[rateIndex] 
		videoContext.playbackRate(rate-0) 
		let videoHeight=710*e.detail.height/e.detail.width 
		this.setData({videoHeight}) 
	},
	async play(e){ 
		let listIndex=e.target.dataset.index 
		if(listIndex==null)return 
		let sourceIndex=this.data.sourceIndex 
		let change={playingSourceIndex:sourceIndex}
		change[`sources[${sourceIndex}].listIndex`]=listIndex 
		change[`sources[${sourceIndex}].list[${listIndex}].selected`]=true 
		this.setData(change) 
		let source=this.data.sources[sourceIndex] 
		let video=source.list[listIndex]
		console.log(video);
		if(video.url.endsWith('.m3u8')){ 
			this.setData({url: video.url}) 
			return
		}
		let url=`${pp.host}${video.url}`
		let html=await app.request({url})
		console.log(html);
		let r, regex=/now="([^"]+)";var pn="[^"]+"; var next="([^"]*)"/
		if(r=regex.exec(html)){
			let change={url: r[1]} 
			change[`sources[${sourceIndex}].list[${listIndex}].url`]=r[1]
			if(r[2])change[`sources[${sourceIndex}].list[${listIndex+1}].url`]=r[2]
			this.setData(change)
		}
	},
	sources(e){ 
		let sourceIndex=e.target.dataset.index 
		if(sourceIndex==null)return 
		let oldIndex=this.data.sourceIndex 
		let change={sourceIndex} 
		if(oldIndex!=null)change[`sources[${oldIndex}].selected`]=false 
		change[`sources[${sourceIndex}].selected`]=true 
		this.setData(change) 
	},
    async onLoad(options) {
		videoContext=wx.createVideoContext('myVideo')
		let index=parseInt(options.index) 
		let pages=getCurrentPages() 
		pp=pages[pages.length-2] 
		console.log(pp.data) 
		let menuIndex=pp.data.menuIndex 
		let menu=pp.data.menus[menuIndex] 
		let type=menu.types[menu.typeIndex] 
		let video=type.list[index] 
		console.log(video)
		let url=`${pp.host}${video.url}` 
		let html=await app.request({ url })
		let r, jj='', regex=/video-info-content">(.+?)<\/div>/s 
		if(r=regex.exec(html)){
			jj='　　'+r[1].replace(/<\/?(p|div|br)[^>]*>|　+/g, '\n')
			.replace(/<[^>]*>/g,'')
			.replace(/&nbsp;/g, ' ')
			.replace(/\s*\n\s*/g, '\n　　')
		}
		let sources=[] 
		regex=/data-dropdown-value="([^"]+)/g 
		while(r=regex.exec(html)){
			sources.push({
				name: r[1], 
			})
		}
		regex=/class="sort-item">(.+?)<\/div>/gs 
		let position=-1
		while(r=regex.exec(html)){
			
			let r2, list=[], reg=/title="([^"]+)" href="([^"]+)/g 
			while(r2=reg.exec(r[1])){ 
				list.push({
					name: r2[1], 
					url: r2[2], 
				})
			}
			sources[++position].list=list 
		}
		this.setData({title: video.title, jj, sources })
    },
})